﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DimensionData.Data2
{
    public class DTreeNode
    {
        private DRow _dRow;

        public DTree Tree { get; set; }
        public DTree NextTree { get; set; }
        public int Level { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public string Formula { get; set; }

        /// <summary>
        /// 下级节点列表
        /// </summary>
        public List<DTreeNode> Nodes { get; set; }

        public DTreeNode ParentNode { get; set; }

        public DTreeNode()
        {
            Nodes = new List<DTreeNode>();
        }

        public override string ToString()
        {
            return string.Format("{0}-{1}({2})", this.Level, this.Name, this.Code);
        }

        /// <summary>
        /// 在node的位置插入个节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="insertNode"></param>
        public void InsertBefore(DTreeNode node, DTreeNode insertNode)
        {
            for (int index = 0; index < Nodes.Count; index++)
            {
                if (Nodes[index] == node)
                {
                    Nodes.Insert(index, insertNode);
                    break;
                }
            }
        }

        public DRow GetDRow()
        {
            if (_dRow == null)
            {
                DRow dRow = new DRow();
                List<DItem> items = new List<DItem>();
                DItem item = new DItem();
                item.Code = this.Code;
                item.Name = this.Name;
                item.Level = this.Level;

                items.Add(item);

                DTreeNode previousTreeNode = null;
                if (this.Tree != null && this.Tree.ParentNode != null)
                {
                    previousTreeNode = this.Tree.ParentNode;
                    while (previousTreeNode != null)
                    {
                        DItem previousItem = new DItem();
                        previousItem.Code = previousTreeNode.Code;
                        previousItem.Name = previousTreeNode.Name;
                        previousItem.Level = previousTreeNode.Level;

                        items.Insert(0, previousItem);

                        if (previousTreeNode.Tree != null && previousTreeNode.Tree.ParentNode != null)
                        {
                            previousTreeNode = previousTreeNode.Tree.ParentNode;
                        }
                        else
                        {
                            previousTreeNode = null;
                        }
                    }
                }

                dRow.Items = items.ToArray();

                _dRow = dRow;
            }
            return _dRow;
        }
    }
}
